package cc.ycws.web.controller;

import cc.ycws.core.domain.*;
import cc.ycws.core.service.*;
import cc.ycws.core.util.DataUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.List;

@Controller
@RequestMapping("/p")
public class PayController {

    Logger logger = Logger.getLogger(PayController.class);
    @Resource
    PayService payService;
    @Resource
    UploadfileService uploadfileService;
    @Resource
    VisitorsService visitorsService;
    @Resource
    CountService countService;
    @Resource
    LocationService locationService;
    DataUtil d = new DataUtil();
    cc.ycws.core.util.Pay comutilpay = new cc.ycws.core.util.Pay();

    @ResponseBody
    @RequestMapping("/buy")
    public String buy(String moblie, String year, String number, String yphone, Pay pay, Uploadfile uploadfile) {
        int years = Integer.parseInt(year);
        int numbers = Integer.parseInt(number);
        uploadfile.setUserid(moblie);
        Uploadfile upload = this.uploadfileService.userid(uploadfile);
        Location moeny = this.locationService.moeny(upload.getYaddress());
        if (moeny != null) {
            if (moeny.getChargingstatus().equals("1")) {
                List<Pay> listpay = this.payService.selectCount(moblie);
                if (years >= 1) {
                    if (listpay.size() >= 1) {
                        return "1";
                    }
                    int Imoeny = Integer.parseInt(moeny.getMoeny());
                    int total = (years + numbers) * Imoeny;
                    String allTotal = String.valueOf(total);
                    String responseStr = this.comutilpay.Moeny(moblie, year, number, yphone, allTotal);
                    JSONObject json = JSONObject.parseObject(responseStr);
                    this.logger.info("下单返回结果:" + json);
                    return json.toString();
                }
                int Imoeny = Integer.parseInt(moeny.getMoeny());
                int total = (years + numbers) * Imoeny;
                String allTotal = String.valueOf(total);
                String responseStr = this.comutilpay.Moeny(moblie, year, number, yphone, allTotal);
                new JSONObject();
                JSONObject json = JSONObject.parseObject(responseStr);
                this.logger.info("下单返回结果:" + json);
                return json.toString();
            }
            if ((moeny == null) || (moeny.getMoeny().equals("0"))) {
                pay.setYear(Integer.valueOf(years));
                pay.setNumber(Integer.valueOf(numbers));
                pay.setTime(DataUtil.data1());
                pay.setState("1");
                pay.setUserid(moblie);
                pay.setMoeny(0);
                pay.setTotal(years + numbers);
                pay.setAddress(moeny.getAddress());
                this.payService.insert(pay);
                return "0";
            }
            int Imoeny = Integer.parseInt(moeny.getMoeny());
            int total = (years + numbers) * Imoeny;
            String allTotal = String.valueOf(total);
            String responseStr = this.comutilpay.Moeny(moblie, year, number,
                    yphone, allTotal);
            new JSONObject();
            JSONObject json = JSONObject.parseObject(responseStr);
            this.logger.info("下单返回结果:" + json);
            return json.toString();
        }
        return "2";
    }

    @RequestMapping({"/Notify"})
    @ResponseBody
    public String Notify(HttpServletRequest request) throws Exception {
        BufferedReader reader = null;
        reader = request.getReader();
        String line = "";
        String xmlString = null;
        StringBuffer inputString = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            inputString.append(line);
        }
        xmlString = inputString.toString();
        if (xmlString != null) {
            this.logger.info("支付回调地址,接收到的数据如下:" + xmlString);
            String trade_state = "trade_state";
            String sub_srade_state = xmlString.substring(
                    xmlString.indexOf(trade_state),
                    xmlString.indexOf(trade_state) + trade_state.length() + 2);
            String state = sub_srade_state.substring(12, 13);
            if ((state.equals("2")) || (state.equals("3"))) {
                this.logger.info("交易成功");
                String attach = "attach";
                String open_id = "open_id";
                String sub_attach = xmlString.substring(
                        xmlString.indexOf(attach), xmlString.indexOf(attach)
                                + attach.length() + 3);
                String sub_open_id = xmlString.substring(
                        xmlString.indexOf(open_id), xmlString.indexOf(open_id)
                                + open_id.length() + 33);
                String year = sub_attach.substring(7, 8);
                String number = sub_attach.substring(8, 9);
                String openid = sub_open_id.substring(8, 40);
                int Iyear = Integer.parseInt(year);
                int Inumber = Integer.parseInt(number);

                Uploadfile uploadfile = new Uploadfile();
                uploadfile.setUserid(openid);
                Uploadfile user = this.uploadfileService.userid(uploadfile);
                int idnumber = Integer.parseInt(user.getIdnumber().substring(0,
                        4));
                String Syear = String.valueOf(idnumber + Iyear);
                uploadfile.setIdnumber(Syear
                        + user.getIdnumber().substring(4, 8));
                uploadfile.setYindex("1");
                uploadfile.setUpdatetime(DataUtil.data1());
                uploadfile.setPayment("1");
                try {
                    this.uploadfileService.updateTime(uploadfile);
                } catch (Exception e) {
                    this.logger.info(e);
                }
                Pay pay = new Pay();
                Location moeny = this.locationService.moeny(user.getYaddress());
                pay.setYear(Integer.valueOf(Iyear));
                pay.setNumber(Integer.valueOf(Inumber));
                pay.setTime(DataUtil.data1());
                pay.setState("1");
                pay.setUserid(openid);
                pay.setMoeny((Iyear + Inumber)
                        * Integer.parseInt(moeny.getMoeny()));
                pay.setTotal(Iyear + Inumber);
                pay.setAddress(moeny.getAddress());
                try {
                    this.payService.insert(pay);
                } catch (Exception e) {
                    this.logger.info(e);
                }
                return "SUCCESS";
            }
            this.logger.info("交易失败");
            return "FAIL";
        }
        this.logger.info("支付回调地址,数据为Null");
        return "FAIL";
    }

    @RequestMapping("/returned")
    public String returned(ModelMap modelMap, HttpServletRequest request) {
        String openid = request.getParameter("openid");
        String phone = request.getParameter("yphone");
        this.logger.info("支付成功返回界面");
        this.logger.info(openid);
        this.logger.info(phone.substring(0, 11));
        return "redirect:/p/success?userid=" + openid + "&yphone=" + phone.substring(0, 11);
    }

    @RequestMapping("/success")
    public String success(Pay pay, Visitors visitors, ModelMap map, String userid, String yphone, Uploadfile uploadfile) {
        int available = 0;
        pay.setUserid(userid);
        List<Pay> num = this.payService.sumN(pay);
        for (Pay p : num) {
            available = p.getNumber().intValue() + available;
        }
        visitors.setUserid(userid);
        List<Visitors> v = this.visitorsService.countC(visitors);
        int existence = v.size();
        uploadfile.setUserid(userid);
        Uploadfile upload = this.uploadfileService.userid(uploadfile);
        List<Count> list = this.countService.Uopendoor(upload.getYid().intValue());
        System.out.println("size===" + list.size());
        map.addAttribute("opensize", Integer.valueOf(list.size()));
        map.addAttribute("name", upload.getYname());
        map.addAttribute("list", list);
        map.addAttribute("numbers", Integer.valueOf(available));
        map.addAttribute("size", Integer.valueOf(existence));
        map.addAttribute("moblie", userid);
        map.addAttribute("yphone", yphone);
        return "csh/homePage";
    }

    @RequestMapping("/doyoupayfor")
    public String doyoupayfor(Uploadfile uploadfile, String userid, String yphone, ModelMap modelMap) {
        uploadfile.setUserid(userid);
        Uploadfile upload = this.uploadfileService.userid(uploadfile);
        if (upload.getYindex().equals("1")) {
            return "redirect:/p/success?userid=" + userid + "&yphone=" + yphone;
        }
        modelMap.addAttribute("moblie", userid);
        modelMap.addAttribute("yphone", yphone);
        return "csh/homePageNo";
    }

    @ResponseBody
    @RequestMapping("/doestheownerpay")
    public String doestheownerpay(Visitors visitors, Pay pay) {
        pay.setUserid(visitors.getUserid());
        List<Pay> num = this.payService.sumN(pay);
        int year = 0;
        for (Pay p : num) {
            year = p.getYear().intValue() + year;
        }
        String Syar = String.valueOf(year);
        return Syar;
    }

    @RequestMapping("/payShow")
    public String payShow(Pay pay, Uploadfile uploadfile, Visitors visitors, ModelMap map) {
        pay.setUserid(visitors.getUserid());
        List<Pay> num = this.payService.sumN(pay);
        int year = 0;
        for (Pay p : num) {
            year = p.getYear().intValue() + year;
        }
        int available = 0;
        List<Pay> nu1 = this.payService.sumN(pay);
        for (Pay p1 : nu1) {
            available = p1.getNumber().intValue() + available;
        }
        visitors.setUserid(visitors.getUserid());
        List<Visitors> v = this.visitorsService.countC(visitors);
        int existence = v.size();
        uploadfile.setUserid(visitors.getUserid());
        Uploadfile user = this.uploadfileService.userid(uploadfile);
        user.setCreatetime(user.getCreatetime().substring(0, 10));
        user.setUpdatetime(user.getUpdatetime().substring(0, 10));
        user.setIdnumber(user.getIdnumber().substring(0, 4) + "-" + user.getIdnumber().substring(4, 6) + "-" + user.getIdnumber().substring(6, 8));
        List<Pay> payList = this.payService.sumN(pay);
        for (Pay p : payList) {
            p.setTime(p.getTime().substring(0, 10));
        }
        map.addAttribute("year", Integer.valueOf(year));
        map.addAttribute("user", user);
        map.addAttribute("numbers", Integer.valueOf(available));
        map.addAttribute("size", Integer.valueOf(existence));
        map.addAttribute("payList", payList);
        return "csh/serivce";
    }
}
